package com.lovemanai.service;


import java.util.List;

import org.hibernate.Hibernate;
import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.junit.Test;

import com.lovemanai.entity.User;
import com.lovemanai.util.HibernateSessionFactory;

public class Demo1 {

	/*
	 * 即时加载 延时加载
	 */
	@Test
	public void test1() {
		
		Session session = HibernateSessionFactory.getSession();
		
		User user = (User) session.get(User.class, 4); 
		
		System.out.println(user.getUname());
		
		//System.out.println(user.getCity().getName());
		
		if(session != null) session.close();
	}
	
	
	public User getUser(int id, boolean flag) {
		Session session = HibernateSessionFactory.getSession();
		
		User user = (User) session.get(User.class, id);
		
		if(flag) {
			/*
			 * 提前加载
			 */
			Hibernate.initialize(user.getCity());
		}
		
		session.close();
		
		return user;
	}

	@Test
	public void test2() {
		
		User user = getUser(4, true);
		
		user.getCity().getName();
	}
	
	/*
	 * 一级缓存
	 */
	@Test
	public void test3() throws InterruptedException {
		Session session = HibernateSessionFactory.getSession();
		
		User user = (User) session.get(User.class, 4);
		
		System.out.println(user.getUname());
		//session.close();
		/*
		 * 关闭session后会清除一级缓存中所有数据
		 * 下面代码则会执行出错
		 */
		User user1 = (User) session.get(User.class, 4);
		//Thread.sleep(1000 * 10);//线程睡眠10秒，关掉mysql服务，此时下面这句话依然可以执行
		System.out.println(user1.getUname());
	}
	
	/*
	 * 二级缓存
	 */
	@Test
	public void test4() {
		SessionFactory sf = HibernateSessionFactory.getSessionFactory();
		
		Session session = sf.openSession();
		
		User user = (User) session.get(User.class, 4);
		System.out.println(user.getUname());
		
		/*
		 * 将从数据库中查出的数据放入二级缓存中
		 * 即使session关闭后也可以从二级缓存中取出数据
		 */
		session.close();
		
		/*
		 * 将数据从二级缓存中清除，再次访问时则需要再次从数据库中查找
		 */
		sf.evict(User.class);
		
		session = sf.openSession();
		User user1 = (User) session.get(User.class, 4);
		
		System.out.println(user1.getUname());
	}
	
	/*
	 * 查询缓存
	 * 
	 */
	@Test
	public void test5() {
		
		SessionFactory sf = HibernateSessionFactory.getSessionFactory();
		
		Session session = sf.openSession();
		
		Query query = session.createQuery("from User");
		
		query.setCacheable(true);//启用查询缓存
		
		List<User> users = query.list();
		for (User user : users) {
			System.out.println(user.getUname());
		}
		
		List<User> users2 = query.list();
	}
	
}
